package com.shqcjd.generalplatformprojectclient.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.shqcjd.generalplatformprojectclient.R;
import com.shqcjd.generalplatformprojectclient.ui.base.BaseActivity;
import com.shqcjd.generalplatformprojectclient.ui.presenter.LoginRegistPresenter;
import com.shqcjd.generalplatformprojectclient.util.ToastUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import uk.co.senab.photoview.PhotoView;

public class ImageActivity extends BaseActivity {
    @BindView(R.id.vp_image)
    ViewPager vpImage;
    private ArrayList<String> mList = new ArrayList<>();
    private int pos = 0;

    @BindView(R.id.btn_image_finish)
    Button btnImageFinish;
    @BindView(R.id.tv_iamge)
    TextView tvIamge;
    @BindView(R.id.btn_image_save)
    Button btnImageSave;


    @Override
    protected LoginRegistPresenter createPresenter() {
        return new LoginRegistPresenter();
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_image;
    }




    @Override
    public void initView() {
        super.initView();
        mList = getIntent().getStringArrayListExtra("imageList");
        pos = getIntent().getIntExtra("pos", 0);
        tvIamge.setText("查看设备图片 "+(pos+1)+"/"+mList.size());

        btnImageFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        List<PhotoView> mImageList = new ArrayList<>();
        PhotoView iv;
        for (int i = 0; i < mList.size(); i++) {
            iv = new PhotoView(this);
            Glide.with(this).load(mList.get(i)).into(iv);
            mImageList.add(iv);
        }
        ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(mImageList, vpImage);
        vpImage.setAdapter(viewPagerAdapter);
        vpImage.setCurrentItem(pos);
        vpImage.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                pos = position;
                tvIamge.setText("查看设备图片 "+(position+1)+"/"+mList.size());
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        btnImageSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Glide.with(ImageActivity.this)
                        .asBitmap()
                        .load(mList.get(pos))
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                saveToSystemGallery(ImageActivity.this, resource);
                                ToastUtils.showShort(ImageActivity.this, "保存成功");
                            }
                        });
            }
        });
    }


    private void saveToSystemGallery(Context context, Bitmap bmp) {
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(), "vgmap");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse(file.getAbsolutePath())));
    }

    private class ViewPagerAdapter extends PagerAdapter {
        private List<PhotoView> images;
        private ViewPager viewPager;

        /**
         * 构造方法，传入图片列表和ViewPager实例
         * @param images
         * @param viewPager
         */

        public ViewPagerAdapter(List<PhotoView> images, ViewPager viewPager){
            this.images  = images;
            this.viewPager = viewPager;
        }

        @Override
        public int getCount() {
            return images.size();//返回一个无限大的值，可以 无限循环
        }

        /**
         * 判断是否使用缓存, 如果返回的是true, 使用缓存. 不去调用instantiateItem方法创建一个新的对象
         */
        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        /**
         * 初始化一个条目
         * @param container
         * @param position 当前需要加载条目的索引
         * @return
         */
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            // 把position对应位置的ImageView添加到ViewPager中
            ImageView iv = images.get(position);
            viewPager.addView(iv);
            // 把当前添加ImageView返回回去.
            return iv;
        }
        /**
         * 销毁一个条目
         * position 就是当前需要被销毁的条目的索引
         */
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            // 把ImageView从ViewPager中移除掉
            viewPager.removeView(images.get(position));

        }
    }
}
